package com.zyy.study.always.code5;

import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

public class Producer implements Runnable{
    private Warehouse warehouse;
    private String producerId;

    public Producer(String producerId, Warehouse warehouse) {
        this.warehouse = warehouse;
        this.producerId = producerId;
        this.warehouse.producerMap.put(producerId, 0);
    }

    /**
     * 获取此生产者生产产品总数
     * @return
     */
    public Integer getProducerCount() {
        return warehouse.producerMap.get(producerId);
    }
    @SneakyThrows
    public void run() {
        Random random = new Random();
        String ware="商品";
        int sno=1;
        StringBuilder wareName = new StringBuilder(ware);
        wareName.append("-").append(producerId).append("-").append(sno);
        warehouse.put(wareName.toString());
        warehouse.producerMap.put(producerId, warehouse.producerMap.get(producerId) + 1);
        System.out.println("生产者:" + producerId + "生产:" + wareName.toString() + "共生产：" + warehouse.producerMap.get(producerId));
        //生产后，休眠0。1～0.5秒
        Thread.sleep(random.ints(1, 1, 5).mapToObj(i -> (long) i / 10).collect(Collectors.toList()).get(0));
    }
}
